import React, { ChangeEvent, JSX } from 'react';
import { Box, Button, TableContainer, Table, TableHead, TableRow, Checkbox, TableBody, TableFooter, IconButton, InputAdornment, TextField } from '@mui/material';
import { useAppSelector, useAppDispatch } from '../../actions/hooks';
import { NulHeaderTableCell, NulTableCell } from '../../components/NulHeaderTable';
import { removeElementFromArray } from '../../util/Arrays';
import { ReactComponent as CreateIcon } from '../../assets/create.svg';
import { ReactComponent as SearchIcon } from '../../assets/search.svg';
import AutorenewIcon from '@mui/icons-material/Autorenew';
import SwitchModelDialog from '../AnalyzeDialog/SwitchModel';
import DeleteIcon from '@mui/icons-material/Delete';
import BatchPredictionIcon from '@mui/icons-material/BatchPrediction';
import { TextEntry, analyzeActions, selectAnalyzeModels, selectAnalyzeResult, selectAnalyzeResultLoaded, selectHistoryEntries } from '../../actions/Analyze';
import moment from 'moment';
import ClearIcon from '@mui/icons-material/Clear';
import AnalyzeSingleTextDialog from '../AnalyzeDialog/AnalyzeSingleText';
import AnalyzeResultDialog from '../AnalyzeDialog/AnalyzeResult';
import '@fontsource/open-sans';


function AnalyzeText(): JSX.Element {

  const dispatch = useAppDispatch();

  const historyEntries = useAppSelector(selectHistoryEntries);
  const selectedModelId = 1;
  const models = useAppSelector(selectAnalyzeModels);
  const analyzeResult = useAppSelector(selectAnalyzeResult);
  const analyzeResultLoaded = useAppSelector(selectAnalyzeResultLoaded);


  const [checkedIdList, setCheckedIdList] = React.useState<number[]>([]);
  const [openSwitchModel, setOpenSwitchModel] = React.useState<boolean>(false);
  const [openAnalyzeSingle, setOpenAnalyzeSingle] = React.useState<boolean>(false);
  const [openAnalyzeResult, setOpenAnalyzeResult] = React.useState<boolean>(false);
  const [filter, setFilter] = React.useState<string>('');

  const inputRef = React.useRef<HTMLInputElement>(null);

  React.useEffect(() => {
    dispatch(analyzeActions.fetchHistory(filter));
  }, [filter, dispatch]);

  React.useEffect(() => {
    if (analyzeResultLoaded) {
      setOpenAnalyzeResult(true);
    }
  }, [analyzeResultLoaded]);

  const handleDelete = (entry: TextEntry) => {
    dispatch(analyzeActions.deleteHistory({
      id: entry.id, filter: filter
    }))
  };

  const handleFileUpload = (event: ChangeEvent<HTMLInputElement>) => {
    if (event.target.files === null) {
      return;
    }
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.onload = (e: ProgressEvent<FileReader>) => {
      const buffer = e.target?.result as string;
      const strings: string[] = buffer.split('\n').map(val => val.trim()).filter(val => val.length > 0);
      dispatch(analyzeActions.analyze({ filter: filter, data: strings }));
    }
    if (file) {
      reader.readAsText(file);
    }
  };


  const headerChecked: boolean = checkedIdList.length !== 0 && checkedIdList.length === historyEntries.length;
  const headerIndeterminate: boolean = checkedIdList.length !== 0 && checkedIdList.length < historyEntries.length;

  return (
    <>
      <Box sx={{ padding: '30px 30px 30px 30px', flex: 'none', flexGrow: 1 }}>
        <Box sx={{
          fontFamily: 'Open Sans',
          fontStyle: 'normal',
          fontWeight: 600,
          fontSize: '22px',
          lineHeight: '125%',
          display: 'flex',
          flexDirection: 'row'
        }}>
          <Box>
            文本分析记录
          </Box>
          <Button
            startIcon={<AutorenewIcon />} sx={{ marginLeft: '10px', textTransform: 'none' }}
            onClick={() => { setOpenSwitchModel(true); }}
          >
            切换模型
          </Button>
        </Box>
        <Box sx={{
          marginTop: '20px', width: '100%', height: '40px', display: 'flex',
          flexDirection: 'row', justifyContent: 'space-between'
        }}>
          <Box sx={{ width: '456px', display: 'flex', flexDirection: 'row' }}>
            <TextField
              size='small'
              fullWidth={true}
              InputProps={{
                startAdornment: (
                  <InputAdornment position='start' sx={{}}>
                    <SearchIcon />
                  </InputAdornment>
                ),
                endAdornment: (
                  <IconButton edge="end" onClick={() => { setFilter(''); }}>
                    <ClearIcon fontSize='small' />
                  </IconButton>
                )
              }}
              placeholder='搜索历史记录...'
              value={filter}
              onChange={(action) => { setFilter(action.target.value); }}
              sx={{
                paddingLeft: '0px'
              }}
            />
          </Box>
          <Box sx={{
            flex: 'none',
            order: 1,
            flexGrow: 0
          }}>
            <Button
              variant="outlined"
              disableElevation
              startIcon={<BatchPredictionIcon />}
              onClick={() => { inputRef?.current?.click(); }}
              sx={{
                height: '40px',
                textTransform: 'none',
                width: '120px',
                marginRight: '20px'
              }}
            >
              批量分析
              <input type='file' ref={inputRef} hidden aria-label='upload-image' onChange={handleFileUpload} />
            </Button>
            <Button
              variant="contained"
              disableElevation
              startIcon={<CreateIcon />}
              onClick={() => {
                setOpenAnalyzeSingle(true);
              }}
              sx={{
                height: '40px',
                textTransform: 'none',
                width: '110px'
              }}
            >
              分 析
            </Button>
          </Box>
        </Box>
        <Box sx={{
          marginTop: '20px',
          width: '100%'
        }}>
          <TableContainer
            sx={{
              width: '100%'
            }}
          >
            <Table
              stickyHeader
              sx={{
                border: '1px solid #DFE4E8',
                borderRadius: '8px',
                fontFamily: 'Open Sans',
                fontStyle: 'normal',
              }}
            >
              <TableHead sx={{ border: '8px 8px 0px 0px' }}>
                <TableRow sx={{
                  height: '42px',
                  padding: 0,
                  width: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  backgroundColor: '#F1F3F5',
                  borderTopLeftRadius: '8px',
                  borderTopRightRadius: '8px'
                }}>
                  <Box sx={{ height: '100%' }}>
                    <NulHeaderTableCell
                      sx={{
                        width: '62px',
                        borderTopLeftRadius: '8px',
                        justifyContent: 'center',
                        flexGrow: 0
                      }}
                    >
                      <Checkbox
                        sx={{
                          width: '42px',
                          display: 'flex',
                          justifyContent: 'center',
                        }}
                        onClick={() => {
                          if (headerChecked) {
                            setCheckedIdList([]);
                          }
                          else {
                            setCheckedIdList(historyEntries.map(entry => entry.id));
                          }
                        }}
                        checked={headerChecked}
                        indeterminate={headerIndeterminate}
                      />
                    </NulHeaderTableCell>
                  </Box>
                  <Box sx={{ display: 'flex', flexDirection: 'row', flexGrow: 1, position: 'relative', height: '100%', paddingRight: '6px' }}>
                    <NulHeaderTableCell sx={{ width: '5%' }}>
                      ID
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '55%' }}>
                      文本
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '15%' }}>
                      时间
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '15%' }}>
                      结果
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '10%' }}>
                      操作
                    </NulHeaderTableCell>
                  </Box>
                </TableRow>
              </TableHead>
              <TableBody
                sx={{
                  minHeight: '390px', maxHeight: '390px', display: 'block', overflowY: 'auto'
                }}
              >
                {historyEntries.map(row => {
                  const checkedIndex: number = checkedIdList.indexOf(row.id);
                  return (
                    <TableRow
                      key={row.id}
                      sx={{
                        width: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        height: '42px'
                      }}
                    >
                      <Box sx={{ height: '100%' }}>
                        <NulTableCell sx={{ width: '62px', justifyContent: 'center', flexGrow: 0 }}>
                          <Checkbox
                            sx={{
                              width: '42px',
                              display: 'flex',
                              justifyContent: 'center',
                            }}
                            checked={checkedIndex !== -1}
                            onChange={(event, checked) => {
                              if (checked) {
                                if (checkedIndex === -1) {
                                  setCheckedIdList([...checkedIdList, row.id]);
                                }
                              }
                              else {
                                if (checkedIndex !== -1) {
                                  setCheckedIdList(removeElementFromArray(checkedIdList, checkedIndex));
                                }
                              }
                            }}
                          />
                        </NulTableCell>
                      </Box>
                      <Box sx={{ display: 'flex', flexDirection: 'row', flexGrow: 1, position: 'relative', height: '100%' }}>

                        <NulTableCell sx={{ width: '5%', display: 'flex' }}>
                          {row.id}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '55%', display: 'flex' }}>
                          {row.text}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '15%', display: 'flex' }}>
                          {moment(row.analyzeTime, true).format('YYYY-MM-DD HH:mm:ss')}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '15%', display: 'flex' }}>
                          {row.result ? '正面' : '负面'}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '10%', display: 'flex' }}>
                          <IconButton onClick={() => { handleDelete(row); }}>
                            <DeleteIcon />
                          </IconButton>
                        </NulTableCell>

                      </Box>
                    </TableRow>
                  );
                })}
              </TableBody>
              <TableFooter
                sx={{
                  minHeight: '34px',
                  maxHeight: '44px',
                  display: 'flex',
                  backgroundColor: '#F1F3F5',
                  borderRadius: '0px 0px 8px 8px',
                }}
              >
                <Box sx={{
                  marginLeft: '20px', fontFamily: 'Inter', fontSize: '14px',
                  paddingTop: '10px', paddingBottom: '10px',
                  color: 'rgb(89, 106, 124)'
                }}>
                  共 {historyEntries.length} 条记录
                </Box>
              </TableFooter>
            </Table>
          </TableContainer>
        </Box>
      </Box>
      <SwitchModelDialog
        open={openSwitchModel}
        onClose={() => { setOpenSwitchModel(false); }}
        models={models}
        onChange={() => { }}
        selectedId={selectedModelId}
      />
      <AnalyzeSingleTextDialog
        open={openAnalyzeSingle}
        onClose={() => { setOpenAnalyzeSingle(false); }}
        onSubmit={(text) => {
          dispatch(analyzeActions.analyze({
            filter: filter,
            data: [text]
          }));
        }}
      />
      <AnalyzeResultDialog
        open={openAnalyzeResult}
        onClose={() => {
          setOpenAnalyzeResult(false);
          dispatch(analyzeActions.clearResult());
        }}
        result={analyzeResult}
      />
    </>
  );
}

export default AnalyzeText;